/*
 * 动态路由生成工具类
 * @Author: bobo
 * @Date: 2021-01-07 09:42:03
 */

/**
 * 判断用户是否有当前路由权限
 * @param {Array} roles 角色数组
 * @param {Array} route 自定义动态路由配置数组
 */
function _hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    // array.some方法用于检测数组中的元素是否满足指定条件（函数提供）
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * 过滤出符合条件的路由配置数组(递归)
 * @param {Array}routes 自定义动态路由配置数组
 * @param {Array}roles 用户角色数组
 */
function _filterDynamicRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = {
      ...route
    }
    if (_hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = _filterDynamicRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res;
}

/**
 * 转换自定义路由到vue-router路由(递归)
 * @param {Array} routeMap 自定义动态路由
 * @return {Array}routes vue-router标准的路由对象集合
 */
function _parseDynamicRouteMap(routeMap = []) {
  const res = []
  routeMap.forEach(route => {
    const tmp = {
      ...route
    }
    const component = tmp.component
    if (tmp.children) {
      tmp.children = _parseDynamicRouteMap(tmp.children)
    }
    if (tmp.component) {
      // 这里必须类似这样写以[@/],不然懒加载会出问题
      // https://segmentfault.com/q/1010000012342377
      tmp.component = () => import(`@/${component}.vue`)
    }
    res.push(tmp)


  })
  return res;
}
const KEY_CACHE_TMP_ROUTE_MAP = 'tmp-route-map';
export default {
  /**
   * 初始化动态路由(登录成功后)
   * 
   * @param {Array} defRoutes 默认静态路由配置数组
   * @param {Array} dynaRoutes 动态路由配置数组
   * @param {Array} roles 用户角色集合
   * @param {VueRouter} vueRouter vue-router实例对象
   */
  initDynamicRoutes(defRoutes = [], dynaRouteMap = [], roles = [], vueRouter) {
    //清除缓存配置
    localStorage.removeItem(KEY_CACHE_TMP_ROUTE_MAP);
    let tmpRouteMap = _filterDynamicRoutes(dynaRouteMap, roles);
    let tmpRoutes = _parseDynamicRouteMap(tmpRouteMap);
    //修改vueRouter对象的routes数据
    vueRouter.options.routes = defRoutes.concat(tmpRoutes);
    vueRouter.addRoutes(tmpRoutes);
    localStorage.setItem(KEY_CACHE_TMP_ROUTE_MAP, JSON.stringify(tmpRouteMap))
  },
  /**
   * 
   * @param {VueRouter} vueRouter  vue-router实例对象
   */
  resetRoutesWhenRefreshed(vueRouter) {
    let routeMapStr = localStorage.getItem(KEY_CACHE_TMP_ROUTE_MAP);
    if (routeMapStr == null || routeMapStr == '') {
      return
    }
    let tmpRouteMap = JSON.parse(routeMapStr);
    if (tmpRouteMap.length === 0) return
    let defRoutes = vueRouter.options.routes;
    let tmpRoutes = _parseDynamicRouteMap(tmpRouteMap);
    vueRouter.options.routes = defRoutes.concat(tmpRoutes);
    vueRouter.addRoutes(tmpRoutes);
  }
}